package com.dhl.rabbitmq.five;

import com.dhl.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 交换机模式，将消息打印到文件夹
 *
 * @author danghailiang
 * @date 2022-12-07
 */
public class ReceiveLogs02 {

    public static final String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws Exception {
        // 1.获取信道
        Channel channel = RabbitUtils.getChannel();
        // 2.创建交换机,设置类型为广播模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        // 3.创建临时队列
        String queueName = channel.queueDeclare().getQueue();
        // 4.交换机和队列绑定
        channel.queueBind(queueName, EXCHANGE_NAME, "");
        // 5.接受消息
        // 创建文件
        File file = new File("F:\\绝笔\\学习笔记总结\\中间件\\rabbitMQ\\笔记\\FANOUT.txt");
        DeliverCallback deliverCallback = (String consumerTag, Delivery message) -> {
            FileUtils.write(file,new String(message.getBody()), StandardCharsets.UTF_8,true);
        };
        channel.basicConsume(queueName, true, deliverCallback, (consumerTag, message) -> {
        });
    }

}
